package zhenbang
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.printing.PrintJob;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	import flash.utils.clearTimeout;
	public class UploadPage extends Sprite
	{
		private static var _main:UploadPage = null;
		public static function get main():UploadPage
		{
			if(_main==null)
				_main = new UploadPage();
			return _main;
		}
		private function get hasQrCodeBtn():Boolean
		{
			return Boolean(Datas.jsonObject && Datas.jsonObject.hasQrCodeBtn==true);
		}
		private function get hasPrintBtn():Boolean
		{
			return Boolean(Datas.jsonObject && Datas.jsonObject.hasPrintBtn==true);
		}
		public function UploadPage()
		{
			_main = this;
			addChild(new Bitmap(test.main.bg.bitmapData));
			//backBtn = new BtnBase(back,test.newBtn("返回"));
			backBtn = new BtnBase(back,new Assets.back_png);
			sendBtn = new BtnBase(toSend,new Assets.send_png);//("上传");
			//printBtn = new BtnBase(toPrint,test.newBtn("打印"));
			printBtn = new BtnBase(toPrint,new Assets.print_png);
			//sendBtn.width = printBtn.width = backBtn.width = 300;
			//sendBtn.height = printBtn.height = backBtn.height = 100;
			//addChild(sendBtn);
			if(hasPrintBtn){
				addChild(printBtn);
			}
			addChild(backBtn);

			tipTxt = ViewSet.makeTxtLine("扫码获取照片",22,0xa41c20);
			addChild(tipTxt).visible = false;
			sendBtn.x = printBtn.x = 1500;
			sendBtn.y = 290;
			printBtn.y = 430;

			width = test.stageW;
			height = test.stageH;
		}
		private var sendBtn:BtnBase;
		private var printBtn:BtnBase;
		private var backBtn:BtnBase;
		private static var qrcode:Bitmap;

		private function toPrint():void
		{
			logs.adds("打印");

			var myPrintJob:PrintJob = new PrintJob();
			if (myPrintJob.start())
			{
				try {
					//myPrintJob.addPage([params]);
					myPrintJob.addPage(photoSprite);
				} catch (error:Error) {
					// Handle error.
				}
				myPrintJob.send();
			}
			else
			{
				//alert("PrintJob canceled");
			}
		}

		private static var hasUploaded:Boolean = false;
		private static var isSaving:Boolean = false;
		private var savingTimeoutId:uint;
		private function toSend():void
		{
			if(isSaving)
				return;
			if(hasUploaded)
			{
				if(bytes)
				{
					bytes.clear();
					bytes = null;
				}
				Toast.show("已上传");
				//sendBtn.visible = false;
				return;
			}
			isSaving = true;
			Toast.show("上传中...",0);
			clearTimeout(savingTimeoutId);
			savingTimeoutId = setTimeout(saving,400);
		}
		private function saving():void
		{
			var bmpd:BitmapData = WriteData.displayObject_bitmapDate(UploadPage.photoSprite);
			bytes = Png.encode(bmpd);
			var filename:String = "image/"+Datas.date2str()+"_"+(Datas.index)+".png";
			photofile = WriteData.write_bytes(filename,bytes);

			clearTimeout(savingTimeoutId);
			//logs.adds("上传生成2维码");

			Window2.photoPlayer.show5s(photofile.url);
			Window2.photoPlayer.addPhotoPath(photofile.url);
			if(FirstPage.photoPlayer){
				FirstPage.photoPlayer.addPhotoPath(photofile.url);
			}


			var _url:String = "http://www.zbvision.cn/signature/upload.php";
			CONFIG::debugging { _url = "http://localhost/upload.php"; }
			var req:URLRequest = new URLRequest(_url);
			req.data = bytes;
			req.method = URLRequestMethod.POST;
			req.contentType = "application/octet-stream";

			var loader:URLLoader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(IOErrorEvent.IO_ERROR, completed);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, completed);
			loader.addEventListener(Event.COMPLETE, completed);
			loader.load(req);
		}

		private static var photofile:File;
		private static var bytes:ByteArray;

		private function completed(e:Event):void
		{
			isSaving = false;
			if(hasQrCodeBtn)
			{
				var remoteUrl:String = null;
				if(e && Event.COMPLETE==e.type){
					var s:String = String(e.target.data);// as String;
					logs.adds(e+"\r\n"+s);
					if(s==null)
					{
						Toast.show(s);
						return;
					}
					var o:Object = null;
					try{
						o = JSON.parse(s);
					}catch(error:Error){
						Toast.show(error.message);
						return;
					}
					if(o==null)
					{
						Toast.show(String(o));
						return;
					}
					if(o.code==1 && o.path!=undefined)
					{
						remoteUrl = "http://www.zbvision.cn/signature/"+o.path;
						Toast.show("上传成功");
					}else{
						Toast.show(o.msg);
						return;
					}

				}else{
					//{"code":0,"msg":"未传值"}
					Toast.show("网络错误");
					return;
				}

				if(hasQrCodeBtn)
				{
					/*
					   var localhost:String = "192.168.1.118";//local host ip 
					   if(System.isWindows){
					   qrcode = QR_Code.str2bmp("http://"+localhost+"/data/"+filename,220,220,0xff000000,0xffffffff);
					   }else{
					   qrcode = QR_Code.str2bmp("http://"+localhost+":8809/data/"+filename,220,220,0xff000000,0xffffffff);
					   }
					 */
					logs.adds(remoteUrl);
					qrcode = QR_Code.str2bmp(remoteUrl,220,220,0xff000000,0xffffffff);
					qrcode.x = 1578;
					qrcode.y = 704;

					addChild(qrcode);

					tipTxt.y = qrcode.y + qrcode.height + 10;
					tipTxt.x = qrcode.x + (qrcode.width-tipTxt.width)/2;
					tipTxt.visible = true;
				}
			}
			Toast.show("上传成功");
			hasUploaded = true;
		}

		private static function delBmp(bmp:Bitmap):void
		{
			if(bmp)
			{
				if(bmp.parent)
					bmp.parent.removeChild(bmp);
				bmp.bitmapData.dispose();
			}
		}

		private static var photoBmp:Bitmap;
		public static var photoSprite:Sprite;
		private static var photoDateTxt:TextField;
		private static var photoIndexTxt:TextField;
		private static var tipTxt:TextField;
		public static function show():void
		{
			hasUploaded = false;
			Datas.countNext();

			main.visible = true;
			test.main.addChild(main);
			main.sendBtn.visible = true;

			delBmp(qrcode);
			qrcode = null;

			if(photoBmp)
			{
				if(photoBmp.parent)
					photoBmp.parent.removeChild(photoBmp);
				//photoBmp.bitmapData.dispose();
				photoBmp = null;
			}
			if(photoSprite == null)
			{
				photoSprite = new Sprite();
				with(photoSprite)
				{
					graphics.beginFill(0xffffff,1.0);
					graphics.drawRoundRect(0, 0, 860, 790,50,50);
					graphics.endFill();
				}
				photoSprite.x = 530;
				photoSprite.y = 160;
				main.addChild(photoSprite);
				photoIndexTxt = ViewSet.makeTxtLine("您是第 位签到来宾",40,0xa41c20);
				photoDateTxt = ViewSet.makeTxtLine("年月日",22,0xa41c20);
				photoSprite.addChild(photoIndexTxt);
				photoSprite.addChild(photoDateTxt);
			}
			photoBmp = new Bitmap(CameraPage.photoBmp.bitmapData);
			photoBmp.width = 810;
			photoBmp.x = photoBmp.y = (photoSprite.width-photoBmp.width)/2;
			photoBmp.scaleY = photoBmp.scaleX;
			photoSprite.addChild(photoBmp);


			var date:Date = new Date();
			photoDateTxt.text = ""+ date.getFullYear() + "年" +(date.getMonth()+1)+"月" + date.getDate() +"日";
			photoDateTxt.x = photoSprite.width - photoDateTxt.width - photoBmp.x;
			photoDateTxt.y = photoSprite.height - photoDateTxt.height - photoBmp.x;

			SignPage.drawBoard.height = photoDateTxt.y - photoBmp.height - photoBmp.y;
			SignPage.drawBoard.scaleX = SignPage.drawBoard.scaleY;
			SignPage.drawBoard.x = photoSprite.width - SignPage.drawBoard.width*1.2;
			SignPage.drawBoard.y = photoDateTxt.y - SignPage.drawBoard.height;
			photoSprite.addChild(SignPage.drawBoard);


			photoIndexTxt.text = "您是第"+(Datas.index)+"位签到来宾";
			photoIndexTxt.x = photoBmp.x;
			photoIndexTxt.y = photoDateTxt.y - photoIndexTxt.height - 10;

			tipTxt.visible = false;


			if(bytes)
			{
				bytes.clear();
				bytes = null;
			}

			if(main.sendBtn.parent==null || main.sendBtn.visible == false)
				main.toSend();


			Datas.saveToFile();
		}

		public static function back():void
		{
			main.visible = false;
			FirstPage.show();
		}
	}
}
